//
//  ProductViewController.m
//  UEAssistant
//
//  Created by mac on 2017/2/24.
//  Copyright © 2017年 youyixinxi. All rights reserved.
//

#import "ProductViewController.h"
#import "OrderTableViewCell.h"
#import "SegProgressView.h"
#import "RCProgressView.h"
#import "MessageViewController.h"
#import "UploadViewController.h"
#import "ProductSubViewController.h"
#import "DetailsModel.h"
#import "MJ_DetailMainController.h"
@interface ProductViewController ()<UITableViewDelegate,UITableViewDataSource,UIGestureRecognizerDelegate>{
    
    NSMutableArray              *_dataSource;
    NSInteger                   _currentPage;
}

@property (nonatomic, strong) UIButton                                      *headView;
@property (nonatomic, strong) UIView                                        *topView;
@property (nonatomic, strong) UIView                                        *midView;
@property (nonatomic, strong) UIView                                        *footView;
@property (nonatomic, strong) UITableView                                   *tableView;
@property (nonatomic, strong) RCProgressView                                *progressView;
@property (nonatomic, strong) UIButton                                      *messageButon;
@property (nonatomic, strong) UIImageView                                   *view_data_nil;
@property (nonatomic, strong) UILabel                                       *text_data_nil;

@end

@implementation ProductViewController

- (void)dealloc{

    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"loginOffClearData" object:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(loginOffnotification) name:@"loginOffClearData" object:nil];
    [self.shadowView setHidden:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUI];
    [self setData];
}

- (void)setUI{

    self.title = @"项目";
    self.view.backgroundColor = RGB(245, 246, 247, 1);

    [self.view addSubview:self.tableView];
    [YhxUtility setExtraCellLineHidden:self.tableView];

    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewTopic)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreTopic)];
    self.tableView.mj_header.automaticallyChangeAlpha = YES;
    self.tableView.mj_footer.automaticallyChangeAlpha = YES;
    
    self.shadowView = [[UIView alloc]initWithFrame:self.view.bounds];
    self.shadowView.backgroundColor = [UIColor colorWithWhite:0.6 alpha:0.3];
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(leftViewResponds)];
    recognizer.delegate = self;
    [self.shadowView addGestureRecognizer:recognizer];
    [self.view addSubview:self.shadowView];
    [self.shadowView setHidden:YES];

}
- (void)leftViewResponds {
    
}

- (void)setData{

    [LSProgressHUD showLoadingToView:self.view];
    _dataSource = [NSMutableArray array];
    _currentPage = 1;
    NSDictionary *dic = @{@"page":@"1",
                          @"limit":@"8",
                          @"ownerId":@"0",
                          @"otherUserId":@"0",
                          
                          };
    [AvailableNetWorking postWithUrl:[userManager.urlCategate stringByAppendingString:productList_connector] params:dic successHandler:^(id responseObject) {
        
//        NSLog(@"productList----%@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            [_dataSource addObjectsFromArray:responseObject[@"result"]];
                [LSProgressHUD hiddenLoading:self.view];
                [self.tableView reloadData];
            
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(245, 246, 247, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
            }
        }
        else{
            
            NSLog(@"message -- %@",responseObject[@"message"]);
            [LSProgressHUD hiddenLoading:self.view];
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(245, 246, 247, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
            }
        }
        if (responseObject) {
            
        }
        
    } falureHandler:^(NSError *error) {
        
        [LSProgressHUD hiddenLoading:self.view];
        if (_dataSource.count == 0) {
            self.tableView.backgroundColor = [UIColor whiteColor];
            [self.tableView addSubview:self.view_data_nil];
            [self.tableView addSubview:self.text_data_nil];
        }
        else{
            self.tableView.backgroundColor = RGB(245, 246, 247, 1);
            [self.view_data_nil removeFromSuperview];
            [self.text_data_nil removeFromSuperview];
            
        }
        
    }];

}


- (void)loginOffnotification{

    //清空原本数据 ------
    [_dataSource removeAllObjects];
    [self.tableView reloadData];
}

#pragma navigationResponds

- (void)hiddenShadowView{
    
    [self.shadowView setHidden:NO];
}

- (void)showShadowView{
    
    [self.shadowView setHidden:YES];
}

- (void)ControlShadowView{
    
//    if ([PSDrawerManager instance].isOpen) {
//        [self hiddenShadowView];
//
//    }
//    else{
//        [self showShadowView];
//    }
}

#pragma ---------- Mjrefresh -------------

- (void)loadNewTopic{
    
    _currentPage = 1;
    NSDictionary *dic = @{@"page":@"1",@"limit":@"8"};
    [AvailableNetWorking postWithUrl:productList_connector params:dic successHandler:^(id responseObject) {
        
//        NSLog(@"productList----%@",responseObject);
        if ([responseObject[@"code"] intValue] == 200) {
            [_dataSource removeAllObjects];
            [_dataSource addObjectsFromArray:responseObject[@"result"]];
            [self.tableView reloadData];
            [self.tableView.mj_header endRefreshing];
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(245, 246, 247, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
                
            }

        }
        else{
            
            [self.tableView.mj_header endRefreshing];
            [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            if (_dataSource.count == 0) {
                self.tableView.backgroundColor = [UIColor whiteColor];
                [self.tableView addSubview:self.view_data_nil];
                [self.tableView addSubview:self.text_data_nil];
            }
            else{
                self.tableView.backgroundColor = RGB(245, 246, 247, 1);
                [self.view_data_nil removeFromSuperview];
                [self.text_data_nil removeFromSuperview];
                
            }

        }
        
    } falureHandler:^(NSError *error) {
        
        [self.tableView.mj_header endRefreshing];
        if (_dataSource.count == 0) {
            self.tableView.backgroundColor = [UIColor whiteColor];
            [self.tableView addSubview:self.view_data_nil];
            [self.tableView addSubview:self.text_data_nil];
        }
        else{
            self.tableView.backgroundColor = RGB(245, 246, 247, 1);
            [self.view_data_nil removeFromSuperview];
            [self.text_data_nil removeFromSuperview];
            
        }

        NSLog(@"%@",error);
    }];
}

- (void)loadMoreTopic{
    
        _currentPage += 1;
        NSString *currentPage = [NSString stringWithFormat:@"%ld",(long)_currentPage];
        NSDictionary *dic = @{@"page":currentPage,@"limit":@"8"};
        [AvailableNetWorking postWithUrl:productList_connector params:dic successHandler:^(id responseObject) {
//            NSLog(@"---------%@",responseObject);
            if ([responseObject[@"code"] intValue] == 200) {
                if (((NSArray *)responseObject[@"result"]).count > 0) {
                    [_dataSource addObjectsFromArray:responseObject[@"result"]];
                    [self.tableView reloadData];
                    [self.tableView.mj_footer endRefreshing];
                }else{
                    
                    _currentPage -= 1;
                    [TopAlertView SetUpbackgroundColor:mainColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:@"已经加载完全部数据" andTitleColor:[UIColor whiteColor] andCancel:NO];
                    [self.tableView.mj_footer endRefreshing];
                }
            }
            else{
                
                _currentPage -= 1;
                [self.tableView.mj_footer endRefreshing];
                [TopAlertView SetUpbackgroundColor:AlertRedColor andStayTime:2.0 andImageName:@"imagePlaceholder" andTitleStr:responseObject[@"message"] andTitleColor:[UIColor whiteColor] andCancel:NO];
            }
        } falureHandler:^(NSError *error) {
            
            _currentPage -= 1;
            [self.tableView.mj_footer endRefreshing];
            NSLog(@"error == == == %@",error);
        }];
   }


#pragma <UITableViewDelegate,UITableViewDataSource>

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _dataSource.count;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return 145*Radio;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    OrderTableViewCell *cell = [[OrderTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    [cell hiddenHisGray];
    [cell.typeImageVV removeFromSuperview];
    [cell.backView setFrame:CGRectMake(10*Radio, 6*Radio, Screen_Width-20*Radio, 145*Radio-12*Radio)];
    cell.nameLabel.text = _dataSource[indexPath.row][@"project_name"];
    [cell.noticView removeFromSuperview];
    [cell.nameLabel setFrame:CGRectMake(16*Radio, 12*Radio, 230*Radio, 30*Radio)];
    cell.wordCount.frame = CGRectMake(cell.backView.frame.size.width - 10*Radio - 80*Radio, cell.noticView.frame.origin.y-8*Radio, 80*Radio, 30*Radio);
    cell.wordCount.textColor = RGB(73, 199, 242, 1);
    cell.wordCount.text = [self judeNullWithString:[NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"wordcount"]]];
    cell.timeLabel.text = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"dealline_time"]];
    cell.langugeType.text = [NSString stringWithFormat:@"%@ -> %@",_dataSource[indexPath.row][@"sourcelangname"],_dataSource[indexPath.row][@"targetlangname"]];
    
    //替换的视图
    _progressView = [[RCProgressView alloc] initWithFrame:CGRectMake(cell.yuImage.frame.origin.x+10*Radio,
                                                                     cell.yuImage.frame.origin.y + cell.yuImage.frame.size.height+20*Radio,
                                                                     Screen_Width - 40*Radio - 100*Radio,
                                                                     8*Radio)];
    CGFloat taskCount = [_dataSource[indexPath.row][@"taskcount"] floatValue];
    CGFloat taskfinishcount = [_dataSource[indexPath.row][@"taskfinishcount"] floatValue];
    CGFloat progress = [self judeNullFloatWithString:[NSString stringWithFormat:@"%f",taskfinishcount/taskCount]];
    [_progressView setProgress:floorf(progress*100)/100];
    [cell addSubview:_progressView];
    
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(_progressView.frame.origin.x+_progressView.frame.size.width+10*Radio, _progressView.frame.origin.y-1, 50*Radio, 10*Radio)];
    label.backgroundColor = [UIColor clearColor];
    label.font = [UIFont systemFontOfSize:FLEXIBLE(12)];
    label.textColor = [UIColor grayColor];
    label.text = @"总进度：";
    label.textAlignment = NSTextAlignmentRight;
    [cell addSubview:label];
    
    UILabel *dataLabel = [[UILabel alloc]initWithFrame:CGRectMake(label.frame.origin.x+label.frame.size.width, _progressView.frame.origin.y-1, 60*Radio, 10*Radio)];
    dataLabel.backgroundColor = [UIColor clearColor];
    dataLabel.font = [UIFont systemFontOfSize:FLEXIBLE(13)];
    dataLabel.textColor = RGB(0, 176, 240, 1);
    NSString *percent = @"%";
    dataLabel.text = [NSString stringWithFormat:@"%.0f%@",floorf(progress*100),percent];
    dataLabel.textAlignment = NSTextAlignmentLeft;
    [cell addSubview:dataLabel];
    
    [cell removeTypeView];
    
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
//    ProductSubViewController *vc = [[ProductSubViewController alloc]init];
    if (_dataSource.count == 0) {
        //数据未加载完成--------
    }else{
        MJ_DetailMainController *vc = [[MJ_DetailMainController alloc] init];
        NSLog(@"pro%@ and edi%@ and%@  and%@",_dataSource[indexPath.row][@"prooffinishcount"],_dataSource[indexPath.row][@"editfinishcount"],_dataSource[indexPath.row][@"taskfinishcount"],_dataSource[indexPath.row][@"tranfinishcount"]);
        
        //新建一个model与后面的subVC共享
        shareData.product_Id = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"project_id"]];
        detailsModel.product_Id = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"project_id"]];
        
        NSMutableArray *dataNeww = [NSMutableArray array];
        [dataNeww addObject:[NSString stringWithFormat:@"%@ - %@",_dataSource[indexPath.row][@"sourcelangname"],_dataSource[indexPath.row][@"targetlangname"]]];
        [dataNeww addObject:@"未统计"];
        [dataNeww addObject:[self judeNullWithString:[NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"wordcount"]]]];
        [dataNeww addObject:[self judeNullWithString:[NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"target_wordcom"]]]];
        [dataNeww addObject:_dataSource[indexPath.row][@"label_idname_list"]];
        [dataNeww addObject:_dataSource[indexPath.row][@"dealline_time"]];
        [detailsModel.dataSource_head removeAllObjects];//先清空上次数据
        detailsModel.dataSource_head = [NSMutableArray arrayWithArray:dataNeww];
        detailsModel.teamName = _dataSource[indexPath.row][@"owner_name"];
        detailsModel.progress_all = [_dataSource[indexPath.row][@"taskfinishcount"] floatValue]/[_dataSource[indexPath.row][@"taskcount"] floatValue];
        detailsModel.progress_prof = [_dataSource[indexPath.row][@"prooffinishcount"] doubleValue]/[_dataSource[indexPath.row][@"proofcount"] doubleValue];
        detailsModel.progress_edit = [_dataSource[indexPath.row][@"editfinishcount"] doubleValue]/[_dataSource[indexPath.row][@"editcount"] doubleValue];
        detailsModel.progress_trans = [_dataSource[indexPath.row][@"tranfinishcount"] doubleValue]/[_dataSource[indexPath.row][@"trancount"] doubleValue];
        detailsModel.ownerId = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"owner_id"]];
        detailsModel.nowStep = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"nowstep"]];
        detailsModel.productName = _dataSource[indexPath.row][@"project_name"];
        detailsModel.remark = _dataSource[indexPath.row][@"remark"];
        detailsModel.memoIsAll = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"ifallmem"]];
        detailsModel.shareIsAll = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"ifallshare"]];
        detailsModel.memtool_id = [NSString stringWithFormat:@"%@",_dataSource[indexPath.row][@"memtool_id"]];
        detailsModel.sourceKey = _dataSource[indexPath.row][@"sourcelangkey"];
        detailsModel.targetlangkey = _dataSource[indexPath.row][@"targetlangkey"];
        vc.teamName = _dataSource[indexPath.row][@"owner_name"];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

-(void)viewDidLayoutSubviews {
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
        
    }
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)])  {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark -- judeNUll

- (NSString *)judeNullWithString:(NSString *)string{
    
    if ([string isEqualToString:@"<null>"]) {
        return @"0字";
    }
    else{
        
        return [NSString stringWithFormat:@"%@字",string];
    }
}

#pragma mark -- judgeFloat

- (CGFloat)judeNullFloatWithString:(id)obj{
    
    if (obj) {
        if ([obj isEqual:[NSNull null]]) {
            CGFloat num = 0;
            return num;
        }
        else{
            
            CGFloat num = [obj floatValue];
            return isnan(num) ? 0 :num;
        }
        
    }else{
        
        return 0;
    }
}

#pragma getter
- (UITableView *)tableView{
    
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width, Screen_Height-49-NAVIGATION_BAR_HEIGHT) style:UITableViewStylePlain];
        _tableView.backgroundColor = RGB(245, 246, 247, 1);
        _tableView.dataSource = self;
        _tableView.delegate = self;
        _tableView.separatorColor = RGB(233, 233, 233, 1);
        _tableView.rowHeight = 100;
        _tableView.scrollIndicatorInsets = _tableView.contentInset;
    }
    return _tableView;
}

- (UIImageView *)view_data_nil{
    
    if (!_view_data_nil) {
        _view_data_nil = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Screen_Width/2+50*Radio, Screen_Width/2)];
        _view_data_nil.image = [UIImage imageNamed:@"项目"];
        _view_data_nil.center = CGPointMake(self.view.center.x, Screen_Height/4);
    }
    return _view_data_nil;
}

- (UILabel *)text_data_nil{
    
    if (!_text_data_nil) {
        _text_data_nil = [[UILabel alloc]initWithFrame:CGRectMake(0, _view_data_nil.frame.origin.y+_view_data_nil.frame.size.height+20*Radio, Screen_Width, 30)];
        _text_data_nil.backgroundColor = [UIColor clearColor];
        _text_data_nil.text = @"暂时还没有参与的项目";
        _text_data_nil.font = [UIFont systemFontOfSize:FLEXIBLE(18)];
        _text_data_nil.textColor = [UIColor grayColor];
        _text_data_nil.textAlignment = NSTextAlignmentCenter;
        
    }
    return _text_data_nil;
}


@end
